package com.book.modules.configure;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * Description：
 *
 * @Author： leo.xiong
 * @CreateDate： 2020/04/02 11:20
 * @Email： leo.xiong@suyun360.com
 * Version：1.0
 */
@Configurable
@Configuration
@EnableAsync
@EnableCaching
public class CoreConfigure {

    @Value("${threed.log.corePoolSize:5}")
    private int logCorePoolSize;

    @Value("${threed.log.maxPoolSize:20}")
    private int logMaxPoolSize;

    @Value("${threed.log.queueCapacity:50}")
    private int logQueueCapacity;

    @Value("${threed.log.keepAliveSeconds:30}")
    private int logKeepAliveSeconds;

    @Value("${threed.log.awaitTerminationSeconds:60}")
    private int logAwaitTerminationSeconds;

    @Value("${threed.log.namePrefix:book-log-thread}")
    private String logNamePrefix;

    @Value("${threed.log.isShutDown:true}")
    private Boolean logIsShutDown;

    @Bean
    public ThreadPoolTaskExecutor asyncLogThreadPoolTaskExecutor() {
        return threadPoolTaskExecutor(logCorePoolSize, logMaxPoolSize, logQueueCapacity, logKeepAliveSeconds, logAwaitTerminationSeconds, logNamePrefix, logIsShutDown);
    }

    @Bean
    @ConditionalOnMissingBean
    public HttpMessageConverters messageConverters(ObjectProvider<HttpMessageConverter<?>> converters) {
        return new HttpMessageConverters(converters.orderedStream().collect(Collectors.toList()));
    }

    private ThreadPoolTaskExecutor threadPoolTaskExecutor(int corePoolSize, int maxPoolSize, int queueCapacity, int keepAliveSeconds, int awaitTerminationSeconds, String namePrefix, Boolean isShutDown) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setAwaitTerminationSeconds(awaitTerminationSeconds);
        executor.setThreadNamePrefix(namePrefix);
        executor.setWaitForTasksToCompleteOnShutdown(isShutDown);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
